<template>
  <div class="right-menu">
    <!-- 左侧区域：菜单按钮 + 左侧钩子 -->
    <div class="left-section flex items-center">
      <el-button v-if="showMenu.indexOf('backend') >= 0" v-auth="['administrator']" link @click="handleNavigation('/admin/#/dashboard')">
        <el-icon>
          <setting />
        </el-icon>
        控制台
      </el-button>
      <el-button v-if="showMenu.indexOf('customer') >= 0" v-auth="['customer']" link @click="handleNavigation('/admin/#/customer')">
        <el-icon>
          <monitor />
        </el-icon>
        客户端
      </el-button>
    </div>
    <!-- 右侧区域：右侧钩子 + 主题切换 + 用户信息 -->
    <div class="right-section flex items-center">
      <div class="theme-switch mx-3 cursor-pointer" @click="toggleTheme">
        <el-switch
          :model-value="configStore.layout.isDark"
          active-action-icon="Moon"
          inactive-action-icon="Sunny"
          inline-prompt
          style="--el-switch-on-color: #2c2c2c; --el-switch-off-color: #f2f2f2"
        ></el-switch>
      </div>

      <!-- 头部用户信息左侧钩子 -->
      <div v-if="settingsStore.hooksLoading" v-loading="true" class="hook-left-loading"></div>
      <div
        v-else-if="settingsStore.hooks['header_user_left_hook']"
        class="hook-content hook-left-content"
        v-html="sanitizeHtml(settingsStore.hooks['header_user_left_hook'])"
      ></div>
      <div class="dk-nav-avatar">
        <el-dropdown class="avatar-container" trigger="click">
          <div class="avatar-wrapper flex items-center">
            <el-avatar :src="userinfo.avatar" class="user-avatar mr1" alt="">
              <i class="el-icon-user-solid" style="font-size: 20px" />
            </el-avatar>
            <div class="username">{{ userinfo.username }}</div>
          </div>
          <template #dropdown>
            <el-dropdown-menu class="user-dropdown">
              <el-dropdown-item v-if="userinfo.userGroup">
                {{ userinfo.userGroup.group_name }}
              </el-dropdown-item>
              <el-dropdown-item v-for="(item, key) in props.userMenus" :key="key" @click="onClickMenu(item)">
                {{ item.title }}
              </el-dropdown-item>
              <el-dropdown-item @click="clear"> 清除缓存 </el-dropdown-item>
              <el-dropdown-item divided @click="logout">
                <span style="display: block">退出</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 头部用户信息右侧钩子 -->
      <div v-if="settingsStore.hooksLoading" v-loading="true" class="hook-right-loading"></div>
      <div
        v-else-if="settingsStore.hooks['header_user_right_hook']"
        class="hook-content hook-right-content"
        v-html="sanitizeHtml(settingsStore.hooks['header_user_right_hook'])"
      ></div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { useConfig } from '@/stores/config'
import { useSettingsStore } from '@/stores/settings'
import router from '@/router'
import { delCache } from '@/api/default/common'
import { ElMessage } from 'element-plus'
import { Moon, Sunny, Setting, Monitor } from '@element-plus/icons-vue'
// 定义组件名称
defineOptions({
  name: 'DkUserInfo'
})

const userStore = useUserStore()
const configStore = useConfig()
const settingsStore = useSettingsStore()
const userinfo = userStore.user
const isDark = ref(configStore.layout.isDark)

const props = defineProps({
  userMenus: {
    default: () => {
      return []
    },
    type: Array
  },
  // backend、customer、dark
  showMenu: {
    default: () => {
      return []
    },
    type: Array
  }
})

// 处理导航点击
const handleNavigation = (url) => {
  window.location.href = url
}

// 切换主题
const toggleTheme = (event) => {
  // 检查浏览器是否支持 View Transition API
  if (!document.startViewTransition) {
    // 不支持则直接切换主题，不添加动画
    document.documentElement.classList.toggle('dark')
    return
  }
  const transition = document.startViewTransition(() => {
    document.documentElement.classList.toggle('dark')
  })

  transition.ready.then(() => {
    const { clientX, clientY } = event

    const endRadius = Math.hypot(Math.max(clientX, innerWidth - clientX), Math.max(clientY, innerHeight - clientY))

    const clipPath = [`circle(0px at ${clientX}px ${clientY}px)`, `circle(${endRadius}px at ${clientX}px ${clientY}px)`]

    const isDark = document.documentElement.classList.contains('dark')

    document.documentElement.animate(
      {
        clipPath: isDark ? clipPath.reverse() : clipPath
      },
      {
        duration: 450,
        easing: 'ease-in',
        pseudoElement: isDark ? '::view-transition-old(root)' : '::view-transition-new(root)'
      }
    )
    configStore.layout.isDark = !configStore.layout.isDark
  })
}
const onClickMenu = (item) => {
  // this.$emit('onClick', item)
}
const logout = async () => {
  userStore.logout()
  router.push('/login')
}
const clear = () => {
  delCache().then((res) => {
    ElMessage.success(res.msg)
  })
}


// 简单的HTML安全处理函数
const sanitizeHtml = (html) => {
  if (!html || typeof html !== 'string') return ''

  // 基础XSS防护：移除script标签和危险属性
  return html
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
    .replace(/on\w+="[^"]*"/gi, '')
    .replace(/on\w+='[^']*'/gi, '')
    .replace(/javascript:/gi, '')
}

// 处理暗黑主题类
const updateThemeClass = (isDark) => {
  if (isDark) {
    document.documentElement.classList.add('dark-theme')
  } else {
    document.documentElement.classList.remove('dark-theme')
  }
}

onMounted(() => {
  // 设置过渡样式
  // setupThemeTransition()

  // 初始化主题类
  updateThemeClass(configStore.layout.isDark)
})

// 监听isDark变化
// watch(
//   () => configStore.layout.isDark,
//   (newValue) => {
//     updateThemeClass(newValue)
//   }
// )
</script>
<style scoped lang="scss">
.right-menu {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-right: 30px;

  // 左侧区域样式
  .left-section {
    flex: 1;
  }

  // 右侧区域样式
  .right-section {
    flex: 1;
    justify-content: flex-end;
  }

  .dk-nav-avatar {
    //头像
    .avatar-container {
      .avatar-wrapper {
        cursor: pointer;
      }
    }
  }

  // Hook内容样式
  .hook-content {
    display: flex;
    align-items: center;
    white-space: nowrap; // 防止文字换行

    // 继承现有的按钮样式，保持一致性
    a,
    .el-button {
      color: var(--el-text-color-primary);
      font-size: 14px;
      padding: 8px 12px;
      margin: 0 4px;
      border-radius: 4px;
      transition: all 0.3s;
      text-decoration: none;
      white-space: nowrap;

      &:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
    }

    // 支持其他HTML标签
    span,
    div {
      display: inline-flex;
      align-items: center;
      margin: 0 4px;
      white-space: nowrap;
    }

    // 开发工具链接样式
    .hook-link {
      color: var(--el-color-primary);
      font-weight: 500;
      padding: 6px 12px;
      margin: 0 4px;
      border-radius: 4px;
      text-decoration: none;
      transition: all 0.3s;

      &:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
    }

    // 时间显示样式
    .hook-time {
      color: var(--el-text-color-regular);
      font-size: 13px;
      margin-right: 12px;
    }

    // 系统状态样式
    .system-status {
      display: inline-flex;
      align-items: center;
      margin-right: 12px;

      .status-dot {
        width: 6px;
        height: 6px;
        background-color: #67c23a;
        border-radius: 50%;
        margin-right: 6px;
      }

      .status-text {
        color: var(--el-text-color-regular);
        font-size: 13px;
      }
    }
  }

  // 左侧hook样式
  .hook-left-content {
    margin-left: 12px;
    margin-right: 8px;
  }

  // 右侧hook样式
  .hook-right-content {
    margin-right: 12px;
  }

  // Loading状态样式
  .hook-left-loading,
  .hook-right-loading {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 暗色主题适配
.dark {
  .right-menu {
    .hook-content {
      a,
      .el-button {
        color: var(--el-text-color-primary);

        &:hover {
          background-color: var(--el-color-primary-light-8);
          color: var(--el-color-primary-light-3);
        }
      }
    }
  }
}
</style>
